package com.ssly.weixin.xichang.admin.controller.api;

import com.ssly.weixin.xichang.common.domain.WeixinArticle;
import com.ssly.weixin.xichang.common.repository.WeixinArticleRepository;
import com.ssly.weixin.xichang.util.JsonResult;
import com.ssly.weixin.xichang.util.R;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpMaterialService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpMaterialServiceImpl;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialCountResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNews;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNewsBatchGetResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.jpa.datatables.mapping.DataTablesInput;
import org.springframework.data.jpa.datatables.mapping.DataTablesOutput;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;


@RestController("admin.weixin-article")
@RequestMapping("/admin/api/weixin-article")
public class WeixinArticleController {
    @Value("${weixin.app-id}")
    private String appID;
    @Value("${weixin.app-secret}")
    private String appSecret;
    @Value("${weixin.proxy}")
    private String proxy;
    @Autowired
    private WeixinArticleRepository weixinArticleRepository;

    @GetMapping
    public DataTablesOutput<WeixinArticle> index(DataTablesInput input) {
        return weixinArticleRepository.findAll(input);
    }

    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable Integer id) {
        weixinArticleRepository.deleteById(id);
        return R.success("删除成功");
    }

    @GetMapping("/sync")
    public JsonResult sync() {
        WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
        config.setAppId(appID); // 设置微信公众号的appid
        config.setSecret(appSecret); // 设置微信公众号的app corpSecret

        WxMpService wxService = new WxMpServiceImpl();// 实际项目中请注意要保持单例，不要在每次请求时构造实例，具体可以参考demo项目
        wxService.setWxMpConfigStorage(config);
        WxMpMaterialService wxMpMaterialService = new WxMpMaterialServiceImpl(wxService);
        try {
            WxMpMaterialCountResult wxMpMaterialCountResult = wxMpMaterialService.materialCount();
            System.out.println("图文素材总数：" + wxMpMaterialCountResult.getNewsCount());
            int newsCount = wxMpMaterialCountResult.getNewsCount();
            int pageSize = 10;
            int createCount = 0;
            int updateCount = 0;
            for (int pageOffset = 0; pageOffset < newsCount; pageOffset += pageSize) {
                System.out.println(pageOffset + ":" + pageSize);
                WxMpMaterialNewsBatchGetResult wxMpMaterialNewsBatchGetResult = wxMpMaterialService.materialNewsBatchGet(pageOffset, pageSize);
                List<WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem> items = wxMpMaterialNewsBatchGetResult.getItems();
                Iterator<WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem> wxMaterialNewsBatchGetNewsItemIterator = items.iterator();
                while (wxMaterialNewsBatchGetNewsItemIterator.hasNext()) {  //执行过程中会执行数据锁定，性能稍差，若在循环过程中要去掉某个元素只能调用iter.remove()方法。

                    WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem wxMaterialNewsBatchGetNewsItem = wxMaterialNewsBatchGetNewsItemIterator.next();
                    List<WxMpMaterialNews.WxMpMaterialNewsArticle> articles = wxMaterialNewsBatchGetNewsItem.getContent().getArticles();
                    Iterator<WxMpMaterialNews.WxMpMaterialNewsArticle> wxMpMaterialNewsArticleIterator = articles.iterator();
                    while (wxMpMaterialNewsArticleIterator.hasNext()) {
                        WxMpMaterialNews.WxMpMaterialNewsArticle wxMpMaterialNewsArticle = wxMpMaterialNewsArticleIterator.next();
//                    使用mediaId title updatedTime 进行联合过滤 同步更新内容
                        String title = wxMpMaterialNewsArticle.getTitle();
                        Timestamp updatedTime = new Timestamp(wxMaterialNewsBatchGetNewsItem.getContent().getUpdatedTime().getTime());
                        String mediaId = wxMaterialNewsBatchGetNewsItem.getMediaId();
                        WeixinArticle weixinArticle;
                        try {
                            weixinArticle = weixinArticleRepository.findTopByMediaIdAndTitle(mediaId, title).get();
                        } catch (NoSuchElementException e) {
                            weixinArticle = new WeixinArticle();
                            createCount++;
                        }
                        if (!updatedTime.equals(weixinArticle.getUpdateTime())) {
                            weixinArticle.setUpdateTime(new Timestamp(wxMaterialNewsBatchGetNewsItem.getContent().getUpdatedTime().getTime()));
                            weixinArticle.setCreateTime(new Timestamp(wxMaterialNewsBatchGetNewsItem.getContent().getCreatedTime().getTime()));
                            weixinArticle.setMediaId(wxMaterialNewsBatchGetNewsItem.getMediaId());

                            weixinArticle.setAuthor(wxMpMaterialNewsArticle.getAuthor());
                            weixinArticle.setContent(wxMpMaterialNewsArticle.getContent().replace("data-src", "src").replace("http://mmbiz.qpic.cn", proxy).replace("https://mmbiz.qpic.cn", proxy));
                            weixinArticle.setTitle(wxMpMaterialNewsArticle.getTitle());
                            weixinArticle.setContentSourceUrl(wxMpMaterialNewsArticle.getContentSourceUrl());
                            weixinArticle.setThumbMediaId(wxMpMaterialNewsArticle.getThumbMediaId());
                            weixinArticle.setNeedOpenComment(wxMpMaterialNewsArticle.getNeedOpenComment());
                            weixinArticle.setOnlyFansCanComment(wxMpMaterialNewsArticle.getOnlyFansCanComment());
                            weixinArticle.setThumbUrl(wxMpMaterialNewsArticle.getThumbUrl());
                            weixinArticle.setUrl(wxMpMaterialNewsArticle.getUrl());
                            weixinArticleRepository.save(weixinArticle);
                            updateCount++;
                        }
                    }
                }
            }

            return R.success("同步成功，新创建" + createCount + "条内容，" + "更新" + updateCount + "条内容");
        } catch (WxErrorException e) {
            e.printStackTrace();
            return R.error("同步失败 " + e.getMessage());
        }
    }

}
